package com.steven.ourcontest.contest.api

import com.steven.ourcontest.contest.bean.MatchCollectionRes
import com.steven.ourcontest.contest.bean.MatchInfoRes
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.net.ApiTransformer
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.team.bean.MatchInfo
import com.steven.ourcontest.team.bean.TeamInfoRes
import io.reactivex.Observable
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ContestApi private constructor() {

    private val mRetrofit: Retrofit
    private val mApiService: ContestApiService

    companion object {
        const val DEFAULT_TIMEOUT = 600
        val instance: ContestApi by lazy {
            ContestApi()
        }
    }

    init {
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(
            DEFAULT_TIMEOUT.toLong(),
            TimeUnit.SECONDS
        )
        builder.addInterceptor {
            val request = it.request()
            val requestBuilder = request.newBuilder()
            requestBuilder.header("uid", LoginController.userId.toString())
                .header("Accept", "application/json")
                .header("userType", LoginController.userType)
            return@addInterceptor it.proceed(requestBuilder.build())
        }
        mRetrofit = Retrofit.Builder()
            .client(builder.build())
            .baseUrl(NetConstants.CHAT_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        mApiService = mRetrofit.create(ContestApiService::class.java)
    }

    fun queryMatch(): Observable<MatchInfoRes> {
        return mApiService.queryMatch().compose(ApiTransformer())
    }

    fun searchMatchDetailById(id: Long): Observable<MatchInfoRes> {
        return mApiService.searchMatchDetailById(id).compose(ApiTransformer())
    }

    fun addHistory(matchId: Long): Observable<EmptyResponse> {
        return mApiService.addHistory(matchId).compose(ApiTransformer())
    }

    fun searchTeamByMatch(matchId: Long): Observable<TeamInfoRes> {
        return mApiService.searchTeamByMatch(matchId).compose(ApiTransformer())
    }

    fun searchHistory(): Observable<MatchInfoRes> {
        return mApiService.searchHistory().compose(ApiTransformer())
    }

    fun searchTop10MatchRecent(): Observable<MatchInfoRes> {
        return mApiService.searchTop10MatchRecent().compose(ApiTransformer())
    }

    fun addMatch(matchInfo: MatchInfo): Observable<EmptyResponse> {
        return mApiService.addMatch(matchInfo).compose(ApiTransformer())
    }
}